<!-- 收到的赞和收藏 -->
<template>
    <MessageList 
        title="收到的赞和收藏"
        :messageList="messageList"
        :unreadCount="unreadCount"
        @item-click="handleItemClick"
    />
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';
import MessageList from '@/components/MessageList.vue';

const router = useRouter();
const messageList = ref([]);

// 未读消息数量
const unreadCount = ref(0);

// 从本地存储加载已读状态
const loadReadStatus = () => {
    try {
        const userId = localStorage.getItem('user_id');
        if (!userId) return {};
        
        const readStatus = localStorage.getItem(`readStatus_${userId}`) || '{}';
        return JSON.parse(readStatus);
    } catch (error) {
        console.error('加载已读状态失败:', error);
        return {};
    }
};

// 保存已读状态到本地存储
const saveReadStatus = (readStatus) => {
    try {
        const userId = localStorage.getItem('user_id');
        if (!userId) return;
        
        localStorage.setItem(`readStatus_${userId}`, JSON.stringify(readStatus));
    } catch (error) {
        console.error('保存已读状态失败:', error);
    }
};

// 标记消息为已读
const markAsRead = (messageId) => {
    const readStatus = loadReadStatus();
    readStatus[messageId] = true;
    saveReadStatus(readStatus);
    
    // 更新消息列表中的已读状态
    const message = messageList.value.find(msg => msg.id === messageId);
    if (message) {
        message.isRead = true;
    }
    
    // 重新计算未读数量
    calculateUnreadCount();
};

// 计算未读消息数量
const calculateUnreadCount = () => {
    const readStatus = loadReadStatus();
    unreadCount.value = messageList.value.filter(msg => !readStatus[msg.id]).length;
    
    // 保存未读数量到localStorage，供News页面使用
    try {
        const userId = localStorage.getItem('user_id');
        if (userId) {
            localStorage.setItem(`zanUnreadCount_${userId}`, unreadCount.value.toString());
        }
    } catch (error) {
        console.error('保存未读数量失败:', error);
    }
};

// 生成消息唯一ID
const generateMessageId = (noteId, userId, type, time) => {
    return `${noteId}_${userId}_${type}_${time}`;
};

// 添加时间计算器函数
const formatTime = (timeStr) => {
    if (!timeStr) return '';
    
    const now = new Date();
    const time = new Date(timeStr);
    
    // 检查时间是否有效
    if (isNaN(time.getTime())) {
        console.error('Invalid time string:', timeStr);
        return '';
    }
    
    // 给时间加上8小时
    time.setHours(time.getHours() + 8);
    
    const diff = now - time; // 时间差（毫秒）
    
    // 十分钟内
    if (diff < 10 * 60 * 1000) {
        return '刚刚';
    }
    
    // 24小时内
    if (diff < 24 * 60 * 60 * 1000) {
        const hours = Math.floor(diff / (60 * 60 * 1000));
        const minutes = Math.floor(diff / (60 * 1000));
        
        if (hours === 0) {
            return `${minutes}分钟前`;
        } else {
            return `${hours}小时前`;
        }
    }
    
    // 本年内
    if (time.getFullYear() === now.getFullYear()) {
        const month = String(time.getMonth() + 1).padStart(2, '0');
        const day = String(time.getDate()).padStart(2, '0');
        return `${month}-${day}`;
    }
    
    // 超过本年
    const year = time.getFullYear();
    const month = String(time.getMonth() + 1).padStart(2, '0');
    const day = String(time.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
};

const onClickDot = (index) => {
    activeIndex.value = index;
}

// 格式化时间为指定格式
const formatDateTime = () => {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}`;
};


// 获取用户的所有笔记
const fetchUserNotes = async () => {
    try {
        const userId = localStorage.getItem('user_id');
        if (!userId) {
            console.error('用户ID不存在');
            return;
        }

        const response = await axios.get(`http://1.14.98.17:8765/api/users/${userId}/notes`);
        if (response.data.success) {
            const notes = response.data.data;
            console.log('获取到用户笔记:', notes);
            
            // 为每个笔记获取点赞和收藏用户列表
            await fetchLikesAndFavoritesForNotes(notes);
        } else {
            console.error('获取用户笔记失败:', response.data.message);
        }
    } catch (error) {
        console.error('获取用户笔记出错:', error);
    }
};

// 获取笔记的点赞和收藏用户列表
const fetchLikesAndFavoritesForNotes = async (notes) => {
    try {
        const allInteractions = [];
        const readStatus = loadReadStatus();
        
        for (const note of notes) {
            try {
                // 获取点赞用户列表
                const likesResponse = await axios.get(`http://1.14.98.17:8765/api/notes/${note.note_id}/likes`);
                if (likesResponse.data.success) {
                    const likes = likesResponse.data.data;
                    console.log(`笔记 ${note.note_id} 的点赞用户:`, likes);
                    
                    // 将点赞用户数据转换为消息列表格式
                    const noteLikes = likes.map(like => {
                        const messageId = generateMessageId(note.note_id, like.user_id, 'like', like.created_at);
                        return {
                            id: messageId,
                            noteId: note.note_id,
                            img: like.user_avatar || '',
                            title: like.user_nickname || '未设置昵称',
                            content: `点赞了你的笔记"${note.title || '无标题'}"`,
                            time: like.created_at,
                            userId: localStorage.getItem('user_id'),
                            type: 'like',
                            isRead: readStatus[messageId] || false
                        };
                    });
                    
                    allInteractions.push(...noteLikes);
                }
                
                // 获取收藏用户列表
                const favoritesResponse = await axios.get(`http://1.14.98.17:8765/api/notes/${note.note_id}/favorites`);
                if (favoritesResponse.data.success) {
                    const favorites = favoritesResponse.data.data;
                    console.log(`笔记 ${note.note_id} 的收藏用户:`, favorites);
                    
                    // 将收藏用户数据转换为消息列表格式
                    const noteFavorites = favorites.map(favorite => {
                        const messageId = generateMessageId(note.note_id, favorite.user_id, 'favorite', favorite.created_at);
                        return {
                            id: messageId,
                            noteId: note.note_id,
                            img: favorite.user_avatar || '',
                            title: favorite.user_nickname || '未设置昵称',
                            content: `收藏了你的笔记"${note.title || '无标题'}"`,
                            time: favorite.created_at,
                            userId: localStorage.getItem('user_id'),
                            type: 'favorite',
                            isRead: readStatus[messageId] || false
                        };
                    });
                    
                    allInteractions.push(...noteFavorites);
                }
            } catch (error) {
                console.error(`获取笔记 ${note.note_id} 点赞/收藏列表失败:`, error);
            }
        }
        
        // 按时间排序，最新的在前面
        allInteractions.sort((a, b) => new Date(b.time) - new Date(a.time));
        
        // 格式化时间显示
        allInteractions.forEach(item => {
            item.time = formatTime(item.time);
        });
        
        messageList.value = allInteractions;
        calculateUnreadCount();
        console.log('最终消息列表:', messageList.value);
        console.log('未读消息数量:', unreadCount.value);
    } catch (error) {
        console.error('获取点赞/收藏列表出错:', error);
    }
};

// 处理点击事件
const handleItemClick = (item) => {
    console.log('点击了消息项:', item);
    
    // 标记消息为已读
    markAsRead(item.id);
    
    // 跳转到MeCont页面，传递noteId和userId参数
    router.push({
        name: 'mecont',
        query: {
            noteId: item.noteId,
            userId: item.userId
        }
    });
};

onMounted(() => {
    fetchUserNotes();
});
</script>
